package com.github.xzb617.rpc.util;

import com.github.xzb617.rpc.entity.Server;
import com.github.xzb617.rpc.httpclient.HttpClientUtil;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URLEncodedUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestClientException;

import java.io.IOException;
import java.net.URI;
import java.util.Map;

public class HttpUtil {

    /**
     * 请求获取数据的超时时间，单位毫秒。如果访问一个接口，多少时间内无法返回数据，就直接放弃此次调用
     */
    private final static int SOCKET_TIMEOUT = 10000;
    /**
     * 设置连接超时时间，单位毫秒
     */
    private final static int CONNECT_TIMEOUT = 10000;

    /**
     * Get请求
     * @param url 地址
     * @param parameters 请求参数
     * @param headers 请求头
     * @param responseType 响应数据的类
     * @param <T>
     * @return
     */
    public static <T> ResponseEntity<T> get(String url, Map<String, String> parameters, Map<String, String> headers, Class<T> responseType) {
        // 使用连接池
        HttpClient httpClient = HttpClientUtil.getInstance();
        HttpGet httpGet = new HttpGet();
        httpGet.setConfig(HttpClientUtil.buildRequestConfig(SOCKET_TIMEOUT, CONNECT_TIMEOUT));
        String strParameters = URLEncodedUtils.format(HttpClientUtil.buildNameValuePair(parameters), "utf-8");
        httpGet.setURI(URI.create(url + "?" + strParameters));
        // 添加请求头
        Header[] httpHeaders = HttpClientUtil.buildHeaders(headers);
        httpGet.setHeaders(httpHeaders);
        // 执行请求，并包装响应结果
        try {
            HttpResponse response = httpClient.execute(httpGet);
            return HttpClientUtil.toResponseEntity(response, responseType);
        }
        catch (IOException e) {
            throw new RestClientException("Failed to send get request to " + url + "， cause by: " + e.getMessage());
        }
        finally {
            // 释放连接
            httpGet.releaseConnection();
        }
    }
}
